package com.fingard.dsp.bank.dbobj.unique;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

import com.fingard.FGBiz;
import com.fingard.db.JDBCHelper;

public class UniqueIdHelper {
	
	public static long getUniqueId(String pKey) throws Exception{
		Connection conn = null;
		try{
			conn = FGBiz.getLocalDbConn();
			return getUniqueId(conn, pKey);
		}catch(Exception ex){
			throw(ex);
		}finally{
			if(conn != null){
				conn.close();
			}
		}
	}

	public static long getUniqueId(Connection pConn, String pKey) throws Exception{
		pKey = pKey.toUpperCase();
		
		for(int i=0;i<10;i++){
			Map<String,Object> unMap=JDBCHelper.execQuerySingle(pConn, "SELECT KEYVALUE,ROWVERSION FROM UNIQUEID WHERE KEYNAME=?",new Object[]{pKey});
			if(unMap!=null&&unMap.size()>0){
				long oldkeyvalue = Long.parseLong(String.valueOf(unMap.get("KEYVALUE")));
				long rowversion = Long.parseLong(String.valueOf(unMap.get("ROWVERSION")));
				long newkeyvalue=oldkeyvalue+1;
				int rowsAff = JDBCHelper.update(pConn, "UPDATE UNIQUEID SET KEYVALUE=?,ROWVERSION=ROWVERSION+1 WHERE KEYNAME=? AND KEYVALUE=? AND ROWVERSION=?",new Object[]{newkeyvalue,pKey,oldkeyvalue,rowversion});
				if(rowsAff==1){
					return newkeyvalue;
				}
			}else{
				try{
					int rowsAff = JDBCHelper.update(pConn, "INSERT INTO UNIQUEID(KEYNAME,KEYVALUE,ROWVERSION)VALUES(?,?,?)",new Object[]{pKey,1,1});
					if(rowsAff==1){
						return 1;
					}
				}catch(SQLException ex){
					FGBiz.limitMsg.exception("getUniqueId", ex, pKey);
				}
			}
		}
		
		throw new Exception("getUniqueId失败");
	}
}
